<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class UploadFileMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response) $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->get('userInfo');
        $tenantId = $user['tenantId'];
        $where = array(
            ['tenantId',$tenantId],
            ['field','site']
        );
        $site_config = DB::table('setting')->where($where)->get()->first();
        $site_config_data = json_decode($site_config->data,true);
        $field = $site_config_data['storage'];
        Config::set('filesystems.default',$field);
        Config::set('filesystems.storage_path',$site_config_data['storagePath']);
        $w = array(
            ['tenantId',$tenantId],
            ['field',$field]
        );
        $res = DB::table('setting')->where($w)->get()->first();
        $config = json_decode($res->data,true);
        if ($field === 'qiniu')
        {
            Config::set('filesystems.disks.qiniu.access_key',$config['access_key']);
            Config::set('filesystems.disks.qiniu.bucket',$config['bucket']);
            Config::set('filesystems.disks.qiniu.domain',$config['domain']);
            Config::set('filesystems.disks.qiniu.secret_key',$config['secret_key']);
        }else if ($field === 'cos')
        {
            Config::set('filesystems.disks.cos.app_id',$config['cos_app_id']);
            Config::set('filesystems.disks.cos.secret_id',$config['cos_secret_id']);
            Config::set('filesystems.disks.cos.secret_key',$config['cos_secret_key']);
            Config::set('filesystems.disks.cos.region',$config['cos_region']);
            Config::set('filesystems.disks.cos.bucket',$config['cos_bucket']);
            Config::set('filesystems.disks.cos.cdn',$config['cos_cdn']);
        }
        return $next($request);
    }
}
